package com.lemon.cloud.security.util;

import com.google.common.collect.Lists;
import com.lemon.cloud.comm.constants.OAuth2Constant;
import com.lemon.cloud.security.model.SecurityUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 安全工具类
 *
 * @author HuangDS
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public SecurityUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUser) {
            return (SecurityUser) principal;
        }
        return SecurityUser.getVisitor();
    }

    /**
     * 获取用户
     */
    public SecurityUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return SecurityUser.getVisitor();
        }
        return getUser(authentication);
    }

    public List<String> getUserAuthorities() {
        SecurityUser user = getUser();
        return Lists.newArrayList(AuthorityUtils.authorityListToSet(user.getAuthorities()));
    }

    public List<String> getRoleCode() {
        return getUserAuthorities().stream()
                .filter(authority -> authority.startsWith(OAuth2Constant.ROLE_PREFIX)).collect(Collectors.toList());
    }
}
